var loginShopProfitSettingList = [];
var loginAllTypeList = [];
var loginAllNameList = [];
var loginSelectTypeValue = null;
var loginShowShopProfitSetting = true;
var loginUploadLayerIndex2;
var loginUploadLayerIndex3;
var loginUploadLayerIndex4;
var loginUploadLayerIndex5;
var loginUploadLayerIndex6;
var loginProductItemList = [];

function loginUploadProductWithoutItem(obj) {
    checkLogin(function (ok) {
        if (ok) {
            var productId = jQuery(obj).attr('productId');
            var platform = jQuery(obj).attr('platform');
            var url = '/onekey/batch?_csrf=' + jQuery("#_csrf").val();
            var classString = '';
            var params = {
                platform: platform,
                productId: productId,
                classString: classString
            };
            params.redirectUrl = window.location.href;
            jQuery.ajax({
                type: 'post',
                url: url,
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(params),
                dataType: "json",
                success: function (res) {
                    if (res.code === 1) {
                        //成功
                        //上传中商品数量加1
                        var newValue;
                        var value = jQuery("#uploadProductCount").html();
                        if (value == '') {
                            newValue = 1;
                        } else {
                            newValue = parseInt(value) + 1;
                        }
                        jQuery("#uploadProductCount").html(newValue);
                        jQuery("#uploadProductCount").css('display', '');
                        layer.msg('已成功加入上传列表');
                    } else if (res.code === 2) {
                        //需要授权
                        var message = res.message;
                        if (res.mapData.authUrl !== ''){
                            window.location.href = res.mapData.authUrl;
                        } else {
                            layer.msg(message, {icon: 7, time:1700});
                        }
                    } else if (res.code === 0) {
                        //失败
                        var d = res.message;
                        jQuery("#loginUploadFailure").html("");
                        var tplLoginFailure = document.getElementById('tplLoginFailure').innerHTML;
                        laytpl(tplLoginFailure).render(d, function (render) {
                            jQuery("#loginUploadFailure").append(render);
                        });
                        loginUploadLayerIndex3 = layer.open({
                            type: 1,
                            title: '提示',
                            area: ['382px', '190px'],
                            shadeClose: true, //点击遮罩关闭
                            content: jQuery("#loginUploadFailure")
                        });
                    } else if (res.code === 3) {
                        //没有设置上传默认设置
                        var d = {};
                        d.message = res.message;
                        d.platform = platform;
                        jQuery("#loginUploadFailureWithNotSetDefault").html("");
                        var tplLoginFailureWithNotSetDefault = document.getElementById('tplLoginFailureWithNotSetDefault').innerHTML;
                        laytpl(tplLoginFailureWithNotSetDefault).render(d, function (render) {
                            jQuery("#loginUploadFailureWithNotSetDefault").append(render);
                        });
                        loginUploadLayerIndex5 = layer.open({
                            type: 1,
                            title: '提示',
                            area: ['382px', '190px'],
                            shadeClose: false, //点击遮罩不关闭
                            content: jQuery("#loginUploadFailureWithNotSetDefault")
                        });
                    }  else if (res.code === 4) {
                        layer.msg(res.message, {icon: 7, time:1700});
                    }
                }
            })
        } else {
            //没有登录
            loginUploadLayerIndex6 = layer.open({
                type: 1,
                title: '提示',
                area: ['382px', '190px'],
                shadeClose: false, //点击遮罩关闭
                content: jQuery("#labFailureWithNoLogin")
            })

        }
    })
}

function loginGetUploadProductWithItem(obj) {
    checkLogin(function (ok) {
        if (ok) {
            loginUploadProductControl(function (flag) {
                if (flag) {
                    var index = layer.load(0, {shade: false});
                    var productId = jQuery(obj).attr('productId');
                    var platform = jQuery(obj).attr('platform');
                    var params = {
                        platform: platform,
                        _csrf: jQuery("#_csrf").val(),
                        status: 0
                    };
                    params.redirectUrl = window.location.href;
                    var url;
                    if (platform == 2) {
                        //有赞
                        url = '/member/query_weidian_item';
                        jQuery.ajax({
                            type: 'get',
                            url: url,
                            data: params,
                            dataType: "json",
                            success: function (res) {
                                var message;
                                if (res.status === 1) {
                                    message = res.message;
                                    loginProductItemList = message;
                                    var d = {};
                                    d.parentItemList = message;
                                    d.platform = platform;
                                    d.productId = productId;
                                    jQuery("#loginUploadSelectItem").html("");
                                    var tplLoginUploadSelectItem = document.getElementById('tplLoginUploadSelectItem').innerHTML;
                                    laytpl(tplLoginUploadSelectItem).render(d, function (render) {
                                        jQuery("#loginUploadSelectItem").append(render);
                                    });
                                    layer.close(index);
                                    loginUploadLayerIndex4 = layer.open({
                                        type: 1,
                                        title: '店铺分类',
                                        area: ['450px', '254px'],
                                        shadeClose: true, //点击遮罩关闭
                                        content: jQuery("#loginUploadSelectItem")
                                    });
                                } else {
                                    message = res.message;
                                    layer.close(index);
                                    if (res.url !== ''){
                                        window.location.href = res.url;
                                    } else {
                                        layer.msg(message, {icon: 7, time:1700});
                                    }
                                }
                            }
                        })
                    } else {
                        //淘宝、1688
                        url = '/member/platform_item_reload';
                        jQuery.ajax({
                            type: 'get',
                            url: url,
                            data: params,
                            dataType: "json",
                            success: function (res) {
                                var message;
                                if (res.status === 1) {
                                    var d = {};
                                    var childItemList = [];
                                    message = res.message;
                                    loginProductItemList = res.message;
                                    if (message.length > 0) {
                                        childItemList = message[0].subClassesList
                                    }
                                    d.parentItemList = message;
                                    d.childItemList = childItemList;
                                    d.platform = platform;
                                    d.productId = productId;
                                    jQuery("#loginUploadSelectItem").html("");
                                    var tplLoginUploadSelectItem = document.getElementById('tplLoginUploadSelectItem').innerHTML;
                                    laytpl(tplLoginUploadSelectItem).render(d, function (render) {
                                        jQuery("#loginUploadSelectItem").append(render);
                                    });
                                    layer.close(index);
                                    loginUploadLayerIndex4 = layer.open({
                                        type: 1,
                                        title: '店铺分类',
                                        area: ['450px', '254px'],
                                        shadeClose: true, //点击遮罩关闭
                                        content: jQuery("#loginUploadSelectItem")
                                    });
                                } else {
                                    message = res.message;
                                    layer.close(index);
                                    layer.msg(message, {icon: 7, time:1700});
                                    if (res.url !== ''){
                                        window.location.href = res.url;
                                    } else {
                                        layer.msg(message, {icon: 7, time:1700});
                                    }
                                }
                            },
                            complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                                layer.close(index);
                            }
                        })
                    }
                } else {
                    var myAppPath = jQuery("#myAppPath").val();
                    var batchCheck = myAppPath + '/onkey/batch/batch_check';
                    jQuery("#gotoLabLogin").attr('href', batchCheck);
                    jQuery("#gotoLabLogin")[0].click();
                }
            })
        } else {
            var myAppPath = jQuery("#myAppPath").val();
            var loginUrl = myAppPath + '/membercenter/login.html';
            window.location.href = loginUrl;
        }
    })
}

function loginChangeUploadItem() {
    var parentItemId = jQuery("#loginFatherItem").val();
    var childItemList = [];
    loginProductItemList.forEach(function (item, index) {
        if (item.id == parentItemId) {
            childItemList = item.subClassesList;
        }
    });
    var childItemListHtml = '';
    if (childItemList.length === 0) {
        //没有子分类
        childItemListHtml = "<option value=''>暂无分类</option>";
    } else {
        childItemList.forEach(function (item, index) {
            var optionHtml = '<option value="' + item.id +'">' + item.name +'</option>'
            childItemListHtml += optionHtml;
        })
    }
    jQuery("#loginChildItem").html(childItemListHtml);
}

function loginReloadUploadItem(platform) {
    var index = layer.load(0, {shade: false});
    var params = {
        platform: platform,
        _csrf: jQuery("#_csrf").val(),
        status: 1
    };
    params.redirectUrl = window.location.href;
    var url;
    if (platform == 2) {
        //有赞
        url = '/member/query_weidian_item';
        jQuery.ajax({
            type: 'get',
            url: url,
            data: params,
            dataType: "json",
            success: function (res) {
                var message = res.message;
                if (res.status === 1) {
                    loginProductItemList = message;
                    var parentItemListHtml = '';
                    if (message.length === 0) {
                        parentItemListHtml = "<option value=''>暂无分类</option>";
                    } else {
                        message.forEach(function (item, index) {
                            var optionHtml = '<option value="' + item.id +'">' + item.name +'</option>';
                            parentItemListHtml += optionHtml;
                        })
                    }
                    layer.close(index);
                    jQuery("#loginFatherItem").html(parentItemListHtml);
                } else {
                    layer.close(index);
                    if (res.url !== ''){
                        window.location.href = res.url;
                    } else {
                        layer.msg(message, {icon: 7, time:1700});
                    }
                }
            }
        })
    } else {
        //淘宝、1688
        url = '/member/platform_item_reload';
        jQuery.ajax({
            type: 'get',
            url: url,
            data: params,
            dataType: "json",
            success: function (res) {
                var message = res.message;
                if (res.status === 1) {
                    var childItemList = [];
                    loginProductItemList = message;
                    if (message.length > 0) {
                        childItemList = message[0].subClassesList
                    }
                    var parentItemListHtml = '';
                    if (message.length === 0) {
                        parentItemListHtml = "<option value=''>暂无分类</option>";
                    } else {
                        message.forEach(function (item, index) {
                            var optionHtml = '<option value="' + item.id +'">' + item.name +'</option>';
                            parentItemListHtml += optionHtml;
                        })
                    }
                    var childItemListHtml = '';
                    if (childItemList.length === 0) {
                        //没有子分类
                        childItemListHtml = "<option value=''>暂无分类</option>";
                    } else {
                        childItemList.forEach(function (item, index) {
                            var optionHtml = '<option value="' + item.id +'">' + item.name +'</option>';
                            childItemListHtml += optionHtml;
                        })
                    }
                    layer.close(index);
                    jQuery("#loginFatherItem").html(parentItemListHtml);
                    jQuery("#loginChildItem").html(childItemListHtml);
                } else {
                    layer.close(index);
                    if (res.url !== ''){
                        window.location.href = res.url;
                    } else {
                        layer.msg(message, {icon: 7, time:1700});
                    }
                }
            },
            complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
                layer.close(index);
            }
        })
    }
}

function loginUploadProductWithItem(productId, platform) {
    checkLogin(function (ok) {
        if (ok) {
            loginUploadProductControl(function (flag) {
                if (flag) {
                    var params ={
                        productId: productId,
                        platform: platform
                    };
                    params.redirectUrl = window.location.href;
                    var classString = "";
                    var url = '/onekey/batch?_csrf=' + jQuery("#_csrf").val();
                    var parentItemId = jQuery("#loginFatherItem").val();
                    var childItemId = jQuery("#loginChildItem").val();
                    if (platform == 2) {
                        //微店
                        if (parentItemId) {
                            classString = parentItemId;
                        }
                    } else {
                        //淘宝、1688
                        if (parentItemId && !childItemId) {
                            //没有子分类
                            classString = '0:' + parentItemId;
                        } else if (parentItemId && childItemId) {
                            //有子分类
                            classString = parentItemId + ':' + childItemId
                        }
                    }
                    params.classString = classString;
                    jQuery.ajax({
                        type: 'post',
                        url: url,
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(params),
                        dataType: "json",
                        success: function (res) {
                            if (res.code === 1) {
                                //成功
                                //上传中商品数量加1
                                var newValue;
                                var value = jQuery("#uploadProductCount").html();
                                if (value == '') {
                                    newValue = 1;
                                } else {
                                    newValue = parseInt(value) + 1;
                                }
                                jQuery("#uploadProductCount").html(newValue);
                                jQuery("#uploadProductCount").css('display', '');
                                layer.msg('已成功加入上传列表');
                                layer.close(loginUploadLayerIndex4);
                            } else if (res.code === 2) {
                                //需要授权
                                var message = res.message;
                                if (res.mapData.authUrl !== ''){
                                    window.location.href = res.mapData.authUrl;
                                } else {
                                    layer.msg(message, {icon: 7, time:1700});
                                }
                            } else if (res.code === 0) {
                                //失败
                                var d = res.message;
                                jQuery("#loginUploadFailure").html("");
                                var tplLoginFailure = document.getElementById('tplLoginFailure').innerHTML;
                                laytpl(tplLoginFailure).render(d, function (render) {
                                    jQuery("#loginUploadFailure").append(render);
                                });
                                loginUploadLayerIndex3 = layer.open({
                                    type: 1,
                                    title: '提示',
                                    area: ['382px', '190px'],
                                    shadeClose: true, //点击遮罩关闭
                                    content: jQuery("#loginUploadFailure")
                                });
                            } else if (res.code === 3) {
                                //没有设置上传默认设置
                                var d = {};
                                d.message = res.message;
                                d.platform = platform;
                                jQuery("#loginUploadFailureWithNotSetDefault").html("");
                                var tplLoginFailureWithNotSetDefault = document.getElementById('tplLoginFailureWithNotSetDefault').innerHTML;
                                laytpl(tplLoginFailureWithNotSetDefault).render(d, function (render) {
                                    jQuery("#loginUploadFailureWithNotSetDefault").append(render);
                                });
                                layer.close(loginUploadLayerIndex4);
                                loginUploadLayerIndex5 = layer.open({
                                    type: 1,
                                    title: '提示',
                                    area: ['382px', '190px'],
                                    shadeClose: false, //点击遮罩不关闭
                                    content: jQuery("#loginUploadFailureWithNotSetDefault"),
                                });
                            } else if (res.code === 4) {
                                layer.msg(res.message, {icon: 7, time:1700});
                            }
                        }
                    })
                } else {
                    var myAppPath = jQuery("#myAppPath").val();
                    var batchCheck = myAppPath + '/onkey/batch/batch_check';
                    jQuery("#gotoLabLogin").attr('href', batchCheck);
                    jQuery("#gotoLabLogin")[0].click();
                }
            })
        } else {
            //没有登录
            var myAppPath = jQuery("#myAppPath").val();
            var loginUrl = myAppPath + '/membercenter/login.html';
            window.location.href = loginUrl;
        }
    })
}

/**
 * 上传风控
 */
function loginUploadProductControl(callback) {
    var url = '/onekey/batch/check?_csrf=' + jQuery("#_csrf").val();
    jQuery.ajax({
        type: 'get',
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (res) {
            var flag = res.flag;
            callback.call(this, flag);
        }
    });
}

/**
 * 判断用户是否登录
 *
 * @param callback
 */
function checkLogin(callback) {
    var checkLoginUrl = '/is_login';
    jQuery.ajax({
        type: 'get',
        url: checkLoginUrl,
        dataType: "json",
        success: function (res) {
            var status = res.status;
            callback.call(this,status);
        }
    })
}

function loginFailureClose() {
    layer.close(loginUploadLayerIndex3);
    layer.close(loginUploadLayerIndex4);
}

function loginUploadProductWithItemCancel() {
    layer.close(loginUploadLayerIndex4)
}

function loginFailureCloseWithNotSetDefault(platform) {
    if (loginShowShopProfitSetting) {
        loginShowShopProfitSetting = false;
        var index = layer.load(0, {shade: false});
        jQuery.ajax({
            type: 'get',
            url: '/member/shop_profit_setting_show',
            dataType: "json",
            success: function (res) {
                var message = res.message;
                var status = res.status;
                if (status === 1 ) {
                    loginShopProfitSettingList = message;
                    jQuery("#loginDefaultSet").html("");
                    var tplLoginDefSet = document.getElementById('tplLoginDefSet').innerHTML;
                    var d = {};
                    var typeList = [];
                    var nameList = [];
                    var messageFirst;
                    message.forEach(function (item, index) {
                        var type = item.type;
                        var name = item.name;
                        typeList.push(type);
                        nameList.push(name);
                        if (item.type == platform) {
                            messageFirst = item;
                        }
                    });
                    if (!messageFirst) {
                        messageFirst = message[0];
                    }
                    loginSelectTypeValue = messageFirst.type;
                    loginAllTypeList = typeList;
                    loginAllNameList = nameList;
                    d.typeList = typeList;
                    d.nameList = nameList;
                    d.message = messageFirst;
                    laytpl(tplLoginDefSet).render(d, function (render) {
                        jQuery("#loginDefaultSet").append(render);
                    });
                    layer.close(loginUploadLayerIndex5);
                    loginUploadLayerIndex2 = layer.open({
                        type: 1,
                        title: '默认设置',
                        area: ['600px', '500px'],
                        shadeClose: true, //点击遮罩关闭
                        content: jQuery("#loginDefaultSet")
                    });
                    loginShowShopProfitSetting = true;
                } else {
                    layer.msg(message, { icon: 5, time: 1500});
                }
            },
            complete: function(XMLHttpRequest, status) {
                layer.close(index);
                loginShowShopProfitSetting = true;
            }
        });
    }
}

function loginSaveDefSet() {
    //获取当前选中平台的默认设置数据
    var setting = [];
    var d = {};
    var profitSetType = jQuery('input:radio[name="loginProfitSetType"]:checked').val();
    var fixProfit = jQuery('#loginFixProfit').val();
    var profitRate = jQuery('#loginProfitRate').val() ? jQuery('#loginProfitRate').val() : null;
    var templateId = jQuery('#loginTemplateSelect').val() ? jQuery('#loginTemplateSelect').val() : null;
    var isWarehouse = jQuery('input:radio[name="loginIsWarehouse"]:checked').val();
    d.profitSetType = profitSetType;
    d.fixProfit = fixProfit;
    d.profitRate = profitRate;
    d.templateId = templateId;
    d.isWarehouse = isWarehouse;
    d.type = loginSelectTypeValue;
    loginShopProfitSettingList.forEach(function (item, index) {
        var message = item.message;
        if (item.type != loginSelectTypeValue) {
            var itemD = {};
            var message = item.message;
            itemD.profitSetType = message.profitSetType;
            itemD.fixProfit = message.fixProfit;
            itemD.profitRate = message.profitRate;
            itemD.templateId = message.templateId ? message.templateId : null;
            itemD.isWarehouse = message.isWarehouse;
            itemD.type = item.type;
            itemD.id = message.id;
            setting.push(itemD);
        } else {
            d.id = message.id
        }
    });
    setting.push(d);
    var params = {
        setting: setting
    };
    var url = '/member/save_shop_profit_setting?_csrf=' + jQuery("#_csrf").val();
    jQuery.ajax({
        type: 'post',
        url: url,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(params),
        dataType: "json",
        success: function (res) {
            if (res.status === 1) {
                layer.msg('设置成功!', {icon: 1, time: 1700});
                layer.close(loginUploadLayerIndex2);
            } else {
                var message = res.message;
                if (!message) {
                    message = '保存默认设置失败!';
                }
                layer.msg(message,{icon: 7, time:1700});
            }
        },
        complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
            if (XMLHttpRequest.status !== 200) {
                //请求异常
                layer.msg('保存默认设置失败!',{icon: 7, time:1700});
            }
        }
    })
}

function loginCloseDefSet() {
    layer.close(loginUploadLayerIndex2)
}

function loginReloadTemplate() {
    var index = layer.load(0, {shade: false});
    var url = '/member/platform_template_reload';
    var params = {
        platform: loginSelectTypeValue,
        _csrf: jQuery("#_csrf").val()
    };
    jQuery.ajax({
        type: 'get',
        url: url,
        data: params,
        dataType: "json",
        success: function (res) {
            if (res.status === 1) {
                var resultList = res.message.freList;
                var shopProfit = {};
                loginShopProfitSettingList.forEach(function (item, index) {
                    if (item.type == loginSelectTypeValue) {
                        shopProfit = item;
                    }
                });
                if (resultList.length > 0) {
                    shopProfit.message.freList = resultList;
                    var selectHtml = '';
                    resultList.forEach(function (item, index) {
                        var optionHtml = '';
                        if (item.templateId == shopProfit.message.templateId) {
                            optionHtml = '<option value="' + item.templateId  + '" selected="selected">' + item.name + '</option>';
                        } else {
                            optionHtml = '<option value="' + item.templateId  + '">' + item.name + '</option>';
                        }
                        selectHtml += optionHtml;
                    });
                } else {
                    shopProfit.message.freList = resultList;
                    var selectHtml = '<option value="">暂无运费模板</option>';
                }
                jQuery("#templateSelect").html(selectHtml);
                layer.close(index);
                layer.msg('运费模板刷新成功!',{icon: 1, time:1700});
            } else {
                var message = res.message ? res.message : '运费模板刷新失败!';
                layer.close(index);
                layer.msg(message, {icon: 7, time:1700});
            }
        },
        complete: function(XMLHttpRequest, status) {
            layer.close(index);
        }
    })
}

function loginChangeTemplate() {
    var selectTemplateId = jQuery('#loginTemplateSelect').val();
    loginShopProfitSettingList.forEach(function (item, index) {
        if (item.type == loginSelectTypeValue) {
            item.message.templateId = selectTemplateId
        }
    })
}

function loginShopProfitSettingChange(type) {
    //平台切换才修改
    if (type != loginSelectTypeValue) {
        //保存上一个选择平台的数据
        var profitSetType = jQuery('input:radio[name="loginProfitSetType"]:checked').val();
        var fixProfit = jQuery('#loginFixProfit').val();
        var profitRate = jQuery('#loginProfitRate').val();
        var templateId = jQuery('#loginTemplateSelect').val();
        var isWarehouse = jQuery('input:radio[name="loginIsWarehouse"]:checked').val();
        loginShopProfitSettingList.forEach(function (item, index) {
            if (loginSelectTypeValue == item.type) {
                item.message.fixProfit = fixProfit;
                item.message.profitRate = profitRate;
                item.message.profitSetType = profitSetType;
                item.message.isWarehouse = isWarehouse;
                if (item.message.freList && item.message.freList.length > 0) {
                    item.message.templateId = templateId;
                }
            }
        });
        loginSelectTypeValue = type;
        var d = {};
        d.typeList = loginAllTypeList;
        d.nameList = loginAllNameList;
        loginShopProfitSettingList.forEach(function (item, index) {
            if (type == item.type) {
                d.message = item
            }
        });
        jQuery("#loginDefaultSet").html("");
        var tplLoginDefSet = document.getElementById('tplLoginDefSet').innerHTML;
        laytpl(tplLoginDefSet).render(d, function (render) {
            jQuery("#loginDefaultSet").append(render);
        });
    }
}

function gotoLabLoginMethod() {
    var myAppPath = jQuery("#myAppPath").val();
    var loginUrl = myAppPath + '/membercenter/login.html';
    jQuery("#gotoLabLogin").attr('href', loginUrl);
    jQuery("#gotoLabLogin")[0].click();
    layer.close(loginUploadLayerIndex6);
}